#!/usr/bin/env python
from standard_script_setup import *
from CIME.utils import copyifnewer, run_bld_cmd_ensure_logging
from CIME.case import Case
from CIME.build import get_standard_makefile_args
import glob

logger = logging.getLogger(__name__)

def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
        usage="""\n{0} [--debug]
OR
{0} --verbose
OR
{0} --help

\033[1mEXAMPLES:\033[0m
    \033[1;32m# Run \033[0m
    > {0}
""" .format (os.path.basename(args[0])),

description=description,

formatter_class=argparse.ArgumentDefaultsHelpFormatter
)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("buildroot",
                        help="build path root")

    parser.add_argument("installpath",
                        help="install path ")

    parser.add_argument("caseroot", nargs="?", default=os.getcwd(),
                        help="Case directory to build")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(args, parser)

    return args.buildroot, args.installpath, args.caseroot

def buildlib(bldroot, installpath, case):
###############################################################################
    caseroot = case.get_value("CASEROOT")
    cimeroot = case.get_value("CIMEROOT")
    mct_dir = os.path.join(cimeroot,"src","externals","mct")
    for _dir in ("mct", "mpeu"):
        if not os.path.isdir(os.path.join(bldroot,_dir)):
            os.makedirs(os.path.join(bldroot,_dir))
        copyifnewer(os.path.join(mct_dir,_dir,"Makefile"),
                    os.path.join(bldroot,_dir,"Makefile"))

    gmake_opts = "-f {} ".format(os.path.join(caseroot,"Tools","Makefile"))
    gmake_opts += " -C {} ".format(bldroot)
    gmake_opts += get_standard_makefile_args(case, shared_lib=True)
    gmake_opts += "MODEL=mct COMP_NAME=mct {}".format(os.path.join(bldroot,"Makefile.conf"))

    gmake_cmd = case.get_value("GMAKE")

    # This runs the mpi-serial configure command
    cmd = "{} {}".format(gmake_cmd, gmake_opts)
    run_bld_cmd_ensure_logging(cmd, logger)

    # Now we run the mct make command
    gmake_opts = "-f {} ".format(os.path.join(mct_dir,"Makefile"))
    gmake_opts += " -C {} ".format(bldroot)
    gmake_opts += " -j {} ".format(case.get_value("GMAKE_J"))
    gmake_opts += " SRCDIR={} ".format(os.path.join(mct_dir))

    cmd = "{} {}".format(gmake_cmd, gmake_opts)
    run_bld_cmd_ensure_logging(cmd, logger)

    for _dir in ("mct", "mpeu"):
        for _file in glob.iglob(os.path.join(bldroot,_dir,"*.a")):
            logger.info("Installing {} to {}".format(_file,installpath))
            copyifnewer(_file, os.path.join(installpath, "lib", os.path.basename(_file)))
        for _file in glob.iglob(os.path.join(bldroot,_dir,"*.mod")):
            logger.info("Installing {} to {}".format(_file,installpath))
            copyifnewer(_file, os.path.join(installpath, "include", os.path.basename(_file)))

def _main(argv, documentation):
    bldroot, installpath, caseroot = parse_command_line(argv, documentation)
    with Case(caseroot) as case:
        buildlib(bldroot, installpath, case)

if (__name__ == "__main__"):
    _main(sys.argv, __doc__)
